package com.sample.android.wifi;

import java.util.ArrayList;

import com.sample.android.wifi.R;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class WifiAdapter extends BaseAdapter
{

	private LayoutInflater			mInflater;
	private Context					mContext;
	private ArrayList<ScanResult>	mArray;

	private static final int[]		mIcons	= { R.drawable.ic_wifi_signal_1,
			R.drawable.ic_wifi_signal_2, R.drawable.ic_wifi_signal_3,
			R.drawable.ic_wifi_signal_4, R.drawable.ic_wifi_lock_signal_1,
			R.drawable.ic_wifi_lock_signal_2, R.drawable.ic_wifi_lock_signal_3,
			R.drawable.ic_wifi_lock_signal_4 };

	private class ViewHolder
	{
		TextView	text1;
		TextView	text2;
		TextView	text3;
		ImageView	image1;
	}

	public WifiAdapter(Context context)
	{
		mContext = context;
		mInflater = LayoutInflater.from(mContext);
		mArray = new ArrayList<ScanResult>();
	}

	public void add(ScanResult object)
	{
		mArray.add(object);
	}

	@Override
	public int getCount()
	{
		return mArray.size();
	}

	@Override
	public ScanResult getItem(int position)
	{
		return mArray.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		final ViewHolder holder;

		if (convertView == null)
		{
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item, null);
			holder.text1 = (TextView) convertView.findViewById(R.id.text1);
			holder.text2 = (TextView) convertView.findViewById(R.id.text2);
			holder.text3 = (TextView) convertView.findViewById(R.id.text3);
			holder.image1 = (ImageView) convertView.findViewById(R.id.image);
			convertView.setTag(holder);
		}
		else
		{
			holder = (ViewHolder) convertView.getTag();
		}

		final ScanResult item = mArray.get(position);
		holder.text1.setText(item.SSID);
		holder.text2.setText(item.capabilities);
		holder.text3.setText(String.valueOf(item.level));
		int strength = WifiManager.calculateSignalLevel(item.level, 4);
		if (item.capabilities.length() > 0)
			strength += 4;
		holder.image1.setImageResource(mIcons[strength]);

		return convertView;
	}

}
